package com.aizhixin.test.common.uitl;

import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.extern.slf4j.Slf4j;

/**  
 * <p>获取微信唯一标识openid</p> 
 */
@Slf4j
public class GetWeChatOpenId {
//获取openid请求
private static String weixinUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=";
    //微信开发者APPID
    private static String appId = "wx6c878fd66bd1d6fd";
    //微信开发者APPSecurity
    private static String appSecurity = "987aa84452025c082d6912caff70d1ae";
    
    /**
     *<p>获取微信唯一标识openId</p> 
     * @Title: getWeixinOpenInfo    
     * @version:V0.1     
     * @param code 微信code（前台获取传入）
     * @return:String 返回openId
     * 
     */
    public static String getWeixinOpenInfo(String code) {
        RestTemplate rest = new RestTemplate();
        StringBuilder sb = new StringBuilder(weixinUrl);
        sb.append(appId).append("&secret=").append(appSecurity);
        sb.append("&js_code=").append(code).append("&grant_type=authorization_code");
        //GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
        String json = rest.getForObject(sb.toString(), String.class);
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        ObjectMapper mapper = new ObjectMapper();
        try {
            JsonNode root = mapper.readTree(json);
            if (root.has("errcode")) {
                log.warn("获取OpenId失败，code:{},errcode:{}, errmsg:{}", code, root.get("errcode").intValue(), root.get("errmsg").textValue());
            } else {
                JsonNode node = root.get("openid");
                if (null != node) {
                    return node.textValue();
                }
            }
        } catch (Exception e) {
            log.warn("调用微信小程序获取openid失败：{}", e);
        }
        return null;
    }
}


